/**
 * File AgentTableHelper.java created by Pablo Díaz Fernández
 * on 12/12/2011 for the project supply-chain-simulator
 */
package org.lsk.pfc.scsim.model.util;

import jade.core.AID;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

/**
 * @author Pablo Díaz Fernández
 * 
 */
public final class AgentTableHelper {

	/**
	 * Table that contains the information of the agents.
	 */
	private Hashtable<String, AgentTableNode> table;

	/**
	 * Constructor of the class.
	 */
	public AgentTableHelper() {
		table = new Hashtable<String, AgentTableNode>();
	}

	/**
	 * Adds a node with the specified name to the table.
	 * 
	 * @param name
	 *            Name of the node to set.
	 * @param aid
	 *            AID of the node to set.
	 */
	public void addAgentTableNode(final String name, final AID aid) {
		table.put(name, new AgentTableNode(name, aid));
	}

	/**
	 * Checks if the table contains the specified key.
	 * 
	 * @param name
	 *            Key to check.
	 * @return <code>true</code> if the key is already inserted.
	 */
	public boolean contains(final String name) {
		return table.containsKey(name);
	}

	/**
	 * Resets all End-Of-Tick flags from the syndicated nodes.
	 */
	public void resetEOT() {
		for (AgentTableNode node : table.values()) {
			node.setEot(false);
		}
	}

	/**
	 * Sets End-Of-Tick flag to the specified node.
	 * 
	 * @param key
	 *            AgentTableNode name.
	 */
	public void setEOT(final String key) {
		table.get(key).setEot(true);
	}

	/**
	 * Sets End-Of-Execution flag to the specified node.
	 * 
	 * @param key
	 *            AgentTableNode name.
	 */
	public void setEOE(final String key) {
		table.get(key).setEoe(true);
	}

	/**
	 * Adds a node to the table.
	 * 
	 * @param key
	 *            Key for the agent info.
	 * @param aid
	 *            AID of the agent.
	 */
	public void addNode(final String key, final AID aid) {
		table.put(key, new AgentTableNode(key, aid));
	}

	/**
	 * Gets the list of nodes that has the End-Of-Execution flag setted to
	 * <code>false</code>.
	 * 
	 * @return List of {@link AID} with nodes.
	 */
	public List<AID> getActive() {
		List<AID> l = new ArrayList<AID>();
		for (AgentTableNode node : table.values()) {
			if (!node.isEoe()) {
				l.add(node.getAid());
			}
		}
		return l;
	}
}
